<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <canvas id="clock" width="200" height="200"></canvas>
  </body>
  <script>
    window.onload = function () {
      var canvas = document.getElementById("clock");
      var ctx = canvas.getContext("2d");
      var centerX = canvas.width / 2;
      var centerY = canvas.height / 2;
      // 将坐标系移动到中心点
      ctx.translate(centerX, centerY);
      function drawClock() {
        var now = new Date();
        var radius = canvas.width / 2 - 5;
        ctx.clearRect(-centerX, -centerY, canvas.width, canvas.height); // 每次绘
        // 制前清空整个画布;
        ctx.beginPath();
        ctx.arc(0, 0, radius, 0, 2 * Math.PI);
        ctx.stroke(); // 绘制钟表数字
        ctx.font = "bold 14px Arial";
        ctx.textAlign = "center";
        ctx.textBaseline = "middle";
        for (let i = 1; i <= 12; i++) {
          var angle = (i * Math.PI) / 6;
          ctx.rotate(angle);
          ctx.translate(0, -radius + 15);
          ctx.rotate(-angle);
          ctx.fillText(i.toString(), 0, 0);
          ctx.rotate(angle);
          ctx.translate(0, radius - 15);
          ctx.rotate(-angle);
        } // 绘制时针
        var hour = now.getHours();
        var minute = now.getMinutes();
        var second = now.getSeconds();
        var hourAngle =
          (((hour % 12) + minute / 60 + second / 3600) * Math.PI) / 6;
        var hourLength = 0.6 * radius;
        var hourX = Math.sin(hourAngle) * hourLength;
        var hourY = -Math.cos(hourAngle) * hourLength;
        ctx.beginPath();
        ctx.moveTo(0, 0);
        ctx.lineTo(hourX, hourY);
        ctx.lineWidth = 4;
        ctx.lineCap = "round";
        ctx.stroke();
        // 绘制分针
        var minuteAngle = ((minute + second / 60) * Math.PI) / 30;
        var minuteLength = 0.8 * radius;
        var minuteX = Math.sin(minuteAngle) * minuteLength;
        var minuteY = -Math.cos(minuteAngle) * minuteLength;

        ctx.beginPath();
        ctx.moveTo(0, 0);
        ctx.lineTo(minuteX, minuteY);
        ctx.lineWidth = 2;
        ctx.stroke();

        // 绘制秒针
        var secondAngle = (second * Math.PI) / 30;
        var secondLength = 0.9 * radius;
        var secondX = Math.sin(secondAngle) * secondLength;
        var secondY = -Math.cos(secondAngle) * secondLength;

        ctx.beginPath();
        ctx.moveTo(0, 0);
        ctx.lineTo(secondX, secondY);
        ctx.lineWidth = 1;
        ctx.strokeStyle = "black"; // 设置颜色
        ctx.stroke();

        // 绘制中央圆点
        ctx.beginPath();
        ctx.arc(0, 0, 5, 0, 2 * Math.PI);
        ctx.fillStyle = "#333"; // 设置颜色
        ctx.fill();

        // 循环绘制
        setTimeout(drawClock, 1000);
      }
      drawClock();
    };
  </script>
</html>
